<template>
    <view class="container">
        <view class="contacts">
            <view class="row-search">
                <view class="search-box block">
                    <icon class="search-icon" type="search" size="14" color="#b2b2b2" />
                    <input v-model="searchText" class="search-input" @input="searchInput" confirm-type="search"
                        placeholder="搜索联系人姓名、企业名称" />
                </view>
                <div class="img-box" @click="goLeave()" v-if="!label">
                    <img class="img-picture" src="@/static/customer-contacts/append.png" alt="">
                </div>
            </view>
            <noData v-if="contactsList?.length === 0" content="暂无相关联系人" />
            <recycle-view>
                <!--            <uni-list>-->
                <view class="" v-for="(item, index) in contactsList" :key="index">
                    <view class="" v-if="item.length">
                        <view class="start" :id='`letter-${index}`'>
                            {{ index }}
                        </view>
                        <uni-swipe-action>
                            <!--                        <uni-list-item>-->
                            <uni-swipe-action-item v-for="(ite, ind) in item" :key="ind">
                                <view :class="['row', ite?.customName ? 'contacts-i' : '']" @click="onEdit(ite)"
                                    v-if="ite?.customName">
                                    <view class="align-flex">
                                        <radio-group @click.stop="onIsChoice(ite.cstContactId)" v-if="choice">
                                            <label>
                                                <radio color="#3E5FF5" :checked="ite.isChoice"
                                                    style="transform:scale(0.7)" />
                                            </label>
                                        </radio-group>
                                        <view>
                                            <view class="info-box">
                                                <view class="phone">
                                                    {{ ite?.companyName }}
                                                </view>
                                                <div style="margin-top: 22rpx;">
                                                    <span v-if="ite?.isSignificance === 1 ? true : false"
                                                        class="identity">重要客户</span>
                                                    <span v-if="ite?.isOpen === 1 ? true : false"
                                                        class="identityc">已开户</span>
                                                </div>
                                                <view class="align-flex" style="margin-top: 22rpx;">
                                                    <view class="name">
                                                        <!--                                                  === 0?ite?.customName.substring(1,ite?.customName.length) : ite?.customName-->
                                                        联系人：{{ ite?.customName.charAt(0) == '#' ?
                                                            ite?.customName?.replace(/#/g,
                                                                '')
                                                            : ite?.customName }}
                                                    </view>
                                                    <!-- <view>
                                                        <img class="sex-img" v-if="ite.sex == 0" src="@/static/male.png"
                                                            alt="" />
                                                        <img class="sex-img" v-if="ite.sex == 1" src="@/static/female.png"
                                                            alt="" />
                                                    </view> -->
                                                </view>
                                            </view>
                                        </view>
                                    </view>
                                    <img v-if="ite.customName" class="phone-img" src="@/static/phone-max.png" alt=""
                                        @click.stop="onMakePhoneCall(ite.phone)" />
                                </view>
                                <!--                            <template v-slot:right>-->
                                <!--                                <view class="delete-box" @click="onDeleteContacts(ite.cstContactId)" v-if="ite.sex !== '2'">-->
                                <!--                                    <img class="delete-img" src="@/static/delete.png" alt="" />-->
                                <!--                                    删除-->
                                <!--                                </view>-->
                                <!--                            </template>-->
                            </uni-swipe-action-item>
                            <!--                        </uni-list-item>-->
                        </uni-swipe-action>
                    </view>
                </view>
                <!--            </uni-list>-->
            </recycle-view>
        </view>
        <view v-if="!choice" class="foot-btn">
            <button class="long-btn" @click="onAddBuildContacts">
                新建联系人
            </button>
        </view>
        <view v-if="choice" class="foot-btn">
            <button class="long-btn" @click="onAddContacts">
                确认添加
            </button>
        </view>
        <!-- choice -->
        <view class="unit-column">
            <view v-for="(item, index) in letter" :key="index" class="unit-column-i" @click="onGoToLetter(item)">
                {{ item }}
            </view>
        </view>
    </view>
</template>
<script setup lang="ts" >
import { onMounted, ref } from 'vue'
import { onLoad, onReachBottom, onShow } from '@dcloudio/uni-app'
import { getCustomerContacts, addContacts, deleteContacts } from '@/api/contact'
import user from '@/utils/user'
import { queryFontLetter } from '@/utils/pinyin'
import noData from '@/components/no-data/no-data.vue'
import { toast, confirm, shake } from '@/utils/util'
const options = ref([
    {
        text: '取消',
        style: {
            backgroundColor: '#007aff'
        }
    }
])
let pageNum = (1)
const selelctList = ref<any>([])
const choice = ref(false)
const list = ref<any>([])
const searchText = ref('')
const dealId = ref()
const label = ref<any>('')
let hasNextPage = (false)
const data2 = ref([])
const contactsList = ref([{
    customName: '王桓泊',
    sex: '0',
    phone: '15930403909',
    userId: 1
}] as any)
const letter = ref(['#', 'A', 'B', 'C', 'D', 'E', 'F', 'E', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'])
const getContactsList = async () => {
    // if (pageNum == 1) {
    //   contactsList.value = {}
    //   pageNum = 1
    //   hasNextPage = true
    //   data2.value = []
    // }
    // pageNum: pageNum,
    // pageSize: 1500
    try {
        const result = await getCustomerContacts({
            searchText: searchText.value,
        })
        // if (!result.hasNextPage) {
        //   hasNextPage = false
        // }
        console.log(result, 'resultresultresultresultresultresultresult')
        list.value = result.map((item: any) => {
            return {
                isChoice: false,
                ...item
            }
        })

        // let arr = []
        // arr.push(...data2.value)
        // arr.push(...list.value)
        // data2.value = arr
        // let deep = JSON.parse(JSON.stringify(arr))
        // list.value = {...contactsList.value, ...list.value}
        console.log(list.value, 'listlistlist355646')
        // console.log(arr, 'arrarrarr')
        // console.log(data2, 'data2data2data2')
        //arr
        contactsList.value = await initShowWorkers(list.value)
        // contactsList.value = contactsList.value.filter((item:any,index:number) => index > 1000)
        console.log(contactsList.value, 'contactsListcontactsListcontactsListcontactsList')
    } catch (err) {
        console.log(err, 'errerrerr')
    }
    // if (result.hasNextPage) {
    //   setTimeout(() => {
    //     getContactsList()
    //     pageNum++
    //   },100)
    // }
}
onLoad(async (options) => {
    if (options.choice) {
        choice.value = true
    }
    console.log(choice.value, 'choicechoice')
    console.log(options, 'optionsoptionsoptions')
    label.value = options.label
    dealId.value = options.dealId
})


onShow(async () => {
    await getContactsList()
})
const searchInput = async () => {
    shake(() => {
        pageNum = 1
        getContactsList()
    })
    console.log(searchText.value, 'searchTextsearchText')
}
// 点击编辑
const onEdit = async (val: any) => {
    console.log(val)
    uni.navigateTo({
        url: '/pages/clientsdetail/clientsdetail?id=' + val.id
    })
}
// 跳转新建
const goLeave = async () => {
    uni.navigateTo({
        url: '/pages/new-contacts/new-contacts'
    })
}
// 删除客户联系人
const onDeleteContacts = async (id: string) => {
    await confirm('确定删除？')
    await deleteContacts({
        id
    })
    toast('删除成功')
    await getContactsList()
    console.log(id, '点击删除啦')
}
// 多选
const onIsChoice = async (cstContactId: any) => {
    console.log(cstContactId, '点击啦')
    const index: any = selelctList.value.indexOf(cstContactId)
    if (index === -1) {
        selelctList.value.push(cstContactId)
    } else {
        selelctList.value.splice(index, 1)
    }
    list.value.forEach((item: any, index: any) => {
        if (item.cstContactId === cstContactId) {
            list.value[index].isChoice = !list.value[index].isChoice
        }
    })
    contactsList.value = await initShowWorkers(list.value)
    console.log(selelctList.value, 'selelctList')
}
// 添加联系人
const onAddContacts = async () => {
    if (selelctList.value.length === 0) {
        toast('请至少选择一个')
        return
    }
    await addContacts({
        cstContactIds: selelctList.value,
        dealId: dealId.value
    })
    toast('添加成功')
    uni.navigateBack({
        delta: 1
    })
}
// 新建联系人
const onAddBuildContacts = async () => {
    uni.navigateTo({
        url: '/pages/new-contacts/new-contacts?isadd=' + true
    })
}
// 拨打电话
const onMakePhoneCall = async (event: string) => {
    uni.makePhoneCall({
        phoneNumber: event
    })
}
// 跳转到字母位置
const onGoToLetter = async (event: string) => {
    uni.vibrateShort({})
    const letter = event
    const query: any = uni.createSelectorQuery()
    console.log(query, 'query')
    console.log('#letter-' + letter, 'letterletterletterletterletterletterletterletterletter')
    query.selectViewport().scrollOffset()
    query.select('#letter-' + letter).boundingClientRect()
    query.exec((res: any) => {
        console.log(res, 'resresresresresresres')
        const scrollTop = res[0].scrollTop
        const top = res[1]?.top ?? 0
        console.log(top + scrollTop, scrollTop, scrollTop + 100000, 'top + scrollToptop + scrollToptop + scrollTop')
        if (top) {
            uni.pageScrollTo({
                scrollTop: top + scrollTop
            })
        } else if (!top && letter === '#' && contactsList.value['#'].length > 0) {
            uni.pageScrollTo({
                scrollTop: 0
            })
        }
    })
}
const initShowWorkers = async (list: any) => {
    // 清洗到字母表中
    const data: any = {
        length: 0
    }
    for (const lettera of letter.value) {
        // 增加对象长度字段判断wxml显示
        data[lettera] = {
            length: 0
        }
    }
    data['#'] = {}
    data['#'].length = 0
    for (const i in list) {
        console.log(i, 'iii');

        // 增加对象长度字段判断wxml显示
        data.length += 1
        // 查询首字母
        const letter = queryFontLetter(list[i]?.companyName)[0][0]
        // console.log(letter, 'letter')
        // console.log(typeof i, '1000000000')
        // if (!label.value && list[i].sex === '2') {
        //     continue
        // }
        // if (list[i].sex === '2') {
        //     // console.log(i, '11111111111111111111111111111111111111111111111111111111111111')
        //     list[i].cstContactId = 130545125166 + Number(i)
        //     // continue
        // }

        list[i].cstContactId = 130545125166 + Number(i)

        const proof = /[A-Z]/
        if (!proof.test(letter)) {
            // console.log(data, 'datadatadata')
            // data.push(list[i])
            // console.log(list[i], 'list[i]list[i]list[i]list[i]list[i]')
            // console.log(data['#'][list[i].cstContactId], 'datadata')
            // list[i].
            data['#'][list[i].cstContactId] = list[i]
            data['#'][list[i].cstContactId].customName = '#' + data['#'][list[i].cstContactId]?.customName
            data['#'].length += 1
            // console.log(data['#'].length, 'lengthlengthlengthlengthlengthlength')
            continue
        }
        // console.log(list[i])
        // list.filter((item:any) => item.cstContactId)
        // console.log(list[i], '1111111111111111111111111111111111111111111111')
        // console.log(list[i], 'listlist1')
        // proof.test(letter)
        // console.log(proof.test(letter), 'cccc')
        // if(proof.test(letter))
        //   console.log(letter, 'data[letter]data[letter]')
        // console.log(proof.test(letter), 'undefinedundefined')
        if (proof.test(letter)) {
            data[letter][list[i].cstContactId] = list[i]
            data[letter].length += 1
        }
    }
    console.log(data, 'datadatadatadatadatadatadatadatadatadatadatadatadatadatadatadata')
    return data
}

// onReachBottom(() => {
//   console.log('打印了吗')
//   // eslint-disable-next-line no-empty
//   if (!hasNextPage) {
//   } else {
//     pageNum += 1
//     getContactsList()
//   }
// })
</script>
<style lang="scss" scoped>
.container {
    // min-height: 100vh;
    padding-bottom: 100rpx;
}

.contacts {
    padding: 30rpx;

    .contacts-i {
        margin: 30rpx 0;
        padding-bottom: 40rpx;
        border-bottom: 1rpx solid #F4F4F7;
    }

    .name {
        color: #202536;
        font-size: 24rpx;
    }

    .phone {
        color: #565868;
        font-size: 32rpx;
        font-weight: 600;
        margin-top: 24rpx;
    }

    .phone-img {
        width: 60rpx;
        height: 60rpx;
        margin-right: 30rpx;
    }

    .sex-img {
        width: 32rpx;
        height: 32rpx;
        margin-left: 12rpx;
    }

    .start {}
}

.unit-column {
    position: fixed;
    right: 2rpx;
    top: 25rpx;

    .unit-column-i {
        margin-bottom: 5rpx;
    }
}

.info-box {
    margin-left: 10rpx;
}

.search-box .search-input {
    background: #FAFAFC;
}

.radio {
    margin-right: 10rpx;
}

.delete-box {
    width: 129rpx;
    height: 82.5%;
    display: flex;
    flex-direction: column;
    align-items: center;
    background: #FF7642;
    color: #fff;
    justify-content: center;

    .delete-img {
        width: 68rpx;
        height: 68rpx;
    }
}

.foot-btn {
    padding-bottom: 20rpx;
}

.row-search {
    display: flex;
    align-items: center;

    .img-box {
        position: relative;
        width: 110rpx;
        height: 90rpx;
        background: $white;
        border-radius: 100%;
        margin: 0 16rpx;

        .img-picture {
            position: absolute;
            left: 0;
            right: 0;
            top: 0;
            bottom: 0;
            margin: auto;
            width: 45rpx;
            height: 45rpx;
        }
    }
}

.identity {
    padding: 3rpx 15rpx;
    background: #EBEFFE;
    border-radius: 6rpx;
    opacity: 1;
    border: 1rpx solid #9EAFFA;
    font-size: 24rpx;
    font-weight: normal;
    color: #3E5FF5;
    line-height: 30rpx;
    margin-left: 8rpx;
}

.identityc {
    padding: 3rpx 15rpx;
    background: rgba(255, 118, 66, 0.1);
    border-radius: 6rpx;
    opacity: 1;
    border: 1rpx solid #FF7642;
    font-size: 24rpx;
    font-weight: normal;
    color: #FF7642;
    line-height: 30rpx;
    margin-left: 8rpx;
}
</style>
